package cn.com.api.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiT_enums;
import cn.com.api.entity.ApiT_member;
import cn.com.api.entity.ApiT_member_entrepreneur;
import cn.com.api.entity.ApiT_member_partner;
import cn.com.api.entity.ApiT_member_partner_task;
import cn.com.api.entity.ApiT_member_task_process;
import cn.com.api.entity.ApiT_order;
import cn.com.api.entity.ApiT_order_detail;
import cn.com.api.entity.ApiU_org;
import cn.com.api.mapper.ApiT_enumsMapper;
import cn.com.api.mapper.ApiT_memberMapper;
import cn.com.api.mapper.ApiT_member_entrepreneurMapper;
import cn.com.api.mapper.ApiT_member_partnerMapper;
import cn.com.api.mapper.ApiT_member_partner_taskMapper;
import cn.com.api.mapper.ApiT_member_task_processMapper;
import cn.com.api.mapper.ApiT_orderMapper;
import cn.com.api.mapper.ApiT_order_detailMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiU_orgMapper;
import cn.com.api.service.ApiMemberService;
import cn.com.api.service.ApiT_memberService;
import cn.com.api.service.ApiT_member_partnerService;
import cn.com.api.service.impl.base.T_member_partnerServiceImplBase;
import cn.com.util.DateUtil;
import cn.com.util.ImageUtils;
import cn.com.util.PageInfo;
import cn.com.util.QRCodeUtils;
import cn.com.util.Util;
import cn.com.util.Utils;

/**
 * 
 **/
@Service
public class ApiT_member_partnerServiceImpl extends T_member_partnerServiceImplBase
		implements ApiT_member_partnerService {
	@Autowired
	private ApiT_member_partnerMapper apiT_member_partnerMapper;
	@Autowired
	private ApiT_enumsMapper apiT_enumsMapper;
	@Autowired
	private ApiT_member_entrepreneurMapper apiT_member_entrepreneurMapper;
	@Autowired
	private ApiT_memberMapper apiT_memberMapper;
	@Autowired
	private ApiT_member_partner_taskMapper apiT_member_partner_taskMapper;
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private ApiU_orgMapper apiU_orgMapper;
	@Autowired
	private ApiT_orderMapper apiT_orderMapper;
	@Autowired
	private ApiT_order_detailMapper apiT_order_detailMapper;
	@Autowired
	private ApiT_member_task_processMapper apiT_member_task_processMapper;
	@Autowired
	private HttpServletRequest request;

	public List<ApiT_member_partner> findT_member_partnersByMap(Map map, PageInfo page) {
		return apiT_member_partnerMapper.findT_member_partnersByMapListPage(map, page);
	}

	@Override
	public List<Map<String, Object>> findMember_partnersByMap(Map map) {
		return apiT_member_partnerMapper.findMember_partnersByMap(map);
	}

	public ApiT_member_partner findTmemberpartnersByMap(Map paramMap) {
		return apiT_member_partnerMapper.findTmemberpartnersByMap(paramMap);
	}

	public Map<String, Object> getPartner(Integer user_id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_id", user_id);
		ApiT_member_partner apiT_member_partner = apiT_member_partnerMapper.findTmemberpartnersByMap(map);
		map.clear();
		if (apiT_member_partner != null) {
			ApiT_order apiT_order = apiT_orderMapper.getpartnerorderinfo(apiT_member_partner.getId() + "");
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("partner", apiT_member_partner);
			Integer queuepartnercount = apiT_member_partnerMapper.getGoldPartnerCount(0,
					apiT_member_partner.getId() + "");
			result.put("queuepartnercount", queuepartnercount);
			result.put("ordernum", apiT_order.getOrdernum());
			result.put("paymoney", apiT_order.getMoney());
			/* 0未支付，1已支付 */
			result.put("paystatus", apiT_order.getZi_status());
			map.put(Utils.DATAS, result);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
			map.put(Utils.MESSAGE, "无申请记录");
		}
		return map;
	}

	// 分配没有推荐人的企业主
	public Integer assignNoRefereeEntre() {
		List<ApiT_member_partner> partner_area_list = this.apiT_member_partnerMapper.findGoldPartnerAreaList();
		for (ApiT_member_partner partner_area : partner_area_list) {
			String area = partner_area.getAddress();
			List<ApiT_member_partner> partner_list = this.apiT_member_partnerMapper.findGoldPartnerListByArea(area);
			List<ApiT_member_entrepreneur> entre_list = this.apiT_member_entrepreneurMapper
					.findEntreListWithoutRefereeByArea(area);

			if (!Util.isNull(entre_list) && !Util.isNull(partner_list) && entre_list.size() > 0
					&& partner_list.size() > 0) {
				Integer entre_list_count = entre_list.size();
				Integer partner_list_count = partner_list.size();
				Date d = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				ApiT_member_entrepreneur entre = new ApiT_member_entrepreneur();
				ApiT_member_partner partner = new ApiT_member_partner();

				for (int j = 0; j < (entre_list_count / partner_list_count + 1); j++) {
					for (int i = 0; i < partner_list_count; i++) {
						Integer index = i % entre_list_count + j * partner_list_count;
						if (index < entre_list_count) {
							String allot_time = df.format(d.getTime() + index * 1000);
							entre = entre_list.get(index);
							partner = partner_list.get(i);

							int result = entre.getUser_id() - partner.getUser_id();
							if (result != 0) {
								ApiT_member entre_member = this.apiT_memberMapper.findT_memberById(entre.getUser_id());
								ApiT_member partner_member = this.apiT_memberMapper
										.findT_memberById(partner.getUser_id());
								ApiT_member_partner_task part_task = this.apiT_member_partner_taskMapper
										.findT_member_partner_taskById(Integer.valueOf(partner.getTask_id()));
								if (!Util.isNull(entre_member) && !Util.isNull(partner_member)) {
									// 更新T_member表
									entre_member.setReferee_uid(partner_member.getPartner_code());
									this.apiT_memberMapper.updateT_member(entre_member);

									// 更新T_member_entrepreneur表
									entre.setReferee_id(partner_member.getPartner_code());
									entre.setReferee_name(partner_member.getC_tname());
									entre.setReferee_type(1);
									String referee_deadline = dff.format(
											d.getTime() + (long) part_task.getAssign_term() * 24 * 60 * 60 * 1000);
									entre.setReferee_deadline(referee_deadline);
									this.apiT_member_entrepreneurMapper.updateT_member_entrepreneur(entre);

									// 更新T_member_partner表，最后轮询分配时间
									partner.setAllot_time(allot_time);
									this.apiT_member_partnerMapper.updateT_member_partner(partner);

								}

							}

						}
					}
				}
			}
		}
		return 1;
	}

	// 申请成为合伙人
	@Transactional
	public Map<String, Object> applyPartner(ApiT_member_partner partner) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		partner.setApply_time(DateUtil.nowTimeToString());
		partner.setIs_pay(0);
		partner.setStatus(0);
		Integer num = 0;
		ApiT_member_partner_task t_member_partner_task = apiT_member_partner_taskMapper
				.findT_member_partner_taskById(Integer.valueOf(partner.getTask_id()));
		t_member_partner_task.setBonus_ratio(t_member_partner_task.getBonus_ratio());
		if (partner.getReferee_id() != null && !"".equals(partner.getReferee_id())) {
			if (validateMember(partner.getReferee_id(), partner.getCorp_id(), map)) {
				map.clear();
				// partner.setStatus(0);
				paramMap.clear();
				paramMap.put("user_id", partner.getUser_id());
				PageInfo page = new PageInfo();
				page.setCurrentPage(1);
				page.setShowCount(5);
				List<ApiT_member_partner> list = apiT_member_partnerMapper.findT_member_partnersByMapListPage(paramMap,
						page);
				if (list != null && list.size() > 0) {// 修改
					partner.setId(list.get(0).getId());
					apiT_member_partnerMapper.updateT_member_partner(partner);
					num = 2;
				} else {
					apiT_member_partnerMapper.insertT_member_partner(partner);
					num = 1;
				}
				paramMap.clear();
				paramMap.put("cid", partner.getUser_id());
				paramMap.put("verify_partner", "2");
				if (partner.getReferee_id() != null && !"".equals(partner.getReferee_id())) {
					paramMap.put("referee_uid", partner.getReferee_id());
				}
				this.apiTmemberMapper.modifyApiTmemberByCuserid(paramMap);
			} else {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "推荐人和企业不匹配");
			}
		} else {
			// 没有推荐人 不轮询
			// ApiU_org org = this.apiU_orgService.findU_orgByCircle();
			//
			// partner.setCorp_id(org.getCorp_code());
			// partner.setCorp_name(org.getCorp_fname());
			// partner.setStatus(0);
			paramMap.clear();
			paramMap.put("user_id", partner.getUser_id());
			PageInfo page = new PageInfo();
			page.setCurrentPage(1);
			page.setShowCount(5);
			List<ApiT_member_partner> list = apiT_member_partnerMapper.findT_member_partnersByMapListPage(paramMap,
					page);
			if (list != null && list.size() > 0) {// 修改
				partner.setId(list.get(0).getId());
				apiT_member_partnerMapper.updateT_member_partner(partner);
				num = 2;
			} else {
				apiT_member_partnerMapper.insertT_member_partner(partner);
				num = 1;
			}
			paramMap.clear();
			paramMap.put("cid", partner.getUser_id());
			paramMap.put("verify_partner", "2");
			if (partner.getReferee_id() != null && !"".equals(partner.getReferee_id())) {
				paramMap.put("referee_uid", partner.getReferee_id());
			}
			this.apiTmemberMapper.modifyApiTmemberByCuserid(paramMap);
			// 更新U_org表Ext1时间，最后一个成员加入时间
			// org.setExt1(Util.CurrentTime());
			// this.apiU_orgService.updateU_org(org);
		}
		if (num != 0) {
			if (num == 1) {// 表示第一次申请，需要创建支付订单
				ApiT_order t_order = new ApiT_order();
				t_order.setTitles("");
				t_order.setShop_id("");
				t_order.setUser_id(partner.getUser_id() + "");
				t_order.setPeisong("");// 1 物流 2 自提

				ApiT_member apiT_member = apiT_memberMapper.findT_memberById(partner.getUser_id());
				if (apiT_member != null) {
					t_order.setName(apiT_member.getC_cname());// 根据userId获取
					t_order.setTel(apiT_member.getC_tel());// 根据userId获取
					t_order.setMobile(apiT_member.getC_mob());// 根据userId获取
					t_order.setEmail(apiT_member.getC_mail());// 根据userId获取
					t_order.setZip(apiT_member.getC_zip());// 根据userId获取
				}
				t_order.setAddress("");
				t_order.setDtime("");// 送达时间 //待定
				t_order.setBz("");

				t_order.setMoney(t_member_partner_task.getDeposit());
				t_order.setAppuser("");
				t_order.setAppdate(DateUtil.nowTimeToString());
				t_order.setRip("");
				t_order.setTitles("申请成为核伙人");
				t_order.setEnable(1);// 未完成订单
				t_order.setZi_status(0);// 未支付
				t_order.setDd_status(1);// 商户未确认
				t_order.setOrdertype(7);// 7-合伙人订单
				String dingDanNo = Utils.getDingDanNo("");
				t_order.setOrdernum(dingDanNo);
				t_order.setSerialflagno(dingDanNo);
				apiT_orderMapper.T_orderInsertion(t_order);
				ApiT_order_detail order_detail = new ApiT_order_detail();
				order_detail.setDid(dingDanNo);
				order_detail.setMoney(t_member_partner_task.getDeposit());
				order_detail.setNum(1);
				order_detail.setTarget_id(partner.getId() + "");
				apiT_order_detailMapper.T_order_detailInsertion(order_detail);
				result.put("ordernum", dingDanNo);
				result.put("paymoney", t_member_partner_task.getDeposit());
				result.put("paystatus", 0);
			} else if (num == 2) {// 修改
				ApiT_order apiT_order = apiT_orderMapper.getpartnerorderinfo(partner.getId() + "");
				result.put("ordernum", apiT_order.getOrdernum());
				result.put("paymoney", apiT_order.getMoney());
				/* 0未支付，1已支付 */
				result.put("paystatus", apiT_order.getZi_status());
			}

			// 获取排队信息(只有申请成为金牌合伙人才会有排队信息)
			if ("1".equals(partner.getTask_id())) {
				List<ApiT_enums> apiT_enums = apiT_enumsMapper.findT_enumssByItem_key("gold_partner_count");
				Integer maxGoldPartnerCount = Integer.valueOf(apiT_enums.get(0).getItem_value());
				Integer queuepartnercount = apiT_member_partnerMapper.getGoldPartnerCount(0, partner.getId() + "");
				result.put("queuepartnercount", queuepartnercount);
				// 现在系统内金牌合伙人数量
				Integer count = apiT_member_partnerMapper.getGoldPartnerCount(1, null);
				// 剩余金牌合伙人数
				Integer remainderpartnercount = maxGoldPartnerCount - count;
				result.put("remainderpartnercount", remainderpartnercount);
			} else {
				result.put("queuepartnercount", -1);
				result.put("remainderpartnercount", 1);
			}
			result.put("partner", partner);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
			map.put(Utils.DATAS, result);
		}
		return map;
	}

	// 金牌合伙人信息
	public Map<String, Object> getGoldPartnersInfo(String partnerid) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 这里是系统设置的，最后从cache中获取
		// 这里是系统设置的，最后从cache中获取
		List<ApiT_enums> apiT_enums = apiT_enumsMapper.findT_enumssByItem_key("gold_partner_count");
		Integer maxGoldPartnerCount = Integer.valueOf(apiT_enums.get(0).getItem_value());
		// 现在系统内金牌合伙人数量
		map.put("maxpartnercount", maxGoldPartnerCount);
		Integer count = apiT_member_partnerMapper.getGoldPartnerCount(1, null);
		Integer queuepartnercount = apiT_member_partnerMapper.getGoldPartnerCount(0, partnerid);
		map.put("remainderpartnercount", (maxGoldPartnerCount - count));
		map.put("queuepartnercount", queuepartnercount);
		// if (maxGoldPartnerCount > count) {// 金牌合伙人数量未满
		// map.put("remainderpartnercount", (maxGoldPartnerCount - count));
		// map.put("queuepartnercount", queuepartnercount);
		// } else {// 金牌合伙人已满后，金牌合伙人待审核状态的人数就是前面排队的人数
		// map.put("remainderpartnercount", 0);
		// map.put("queuepartnercount", queuepartnercount);
		// }
		return map;
	}

	/**
	 * 验证机构和推荐人
	 * 
	 */
	public Boolean validateMember(String partner_code, String corp_code, Map<String, Object> map) {
		Boolean result = false;
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("partner_code", partner_code);
		List<ApiT_member> list = apiT_memberMapper.findT_membersByMap(conditions);
		if (list != null && list.size() > 0) {
			ApiT_member apiT_member = list.get(0);
			if (apiT_member.getVerify_partner() == 1) {
				conditions.clear();
				conditions.put("user_id", apiT_member.getC_id());
				PageInfo page = new PageInfo();
				page.setCurrentPage(1);
				page.setShowCount(5);
				List<ApiT_member_partner> partners = apiT_member_partnerMapper
						.findT_member_partnersByMapListPage(conditions, page);
				if (partners != null && partners.size() > 0) {
					if (corp_code.equals(partners.get(0).getCorp_id())) {
						result = true;
						map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
						map.put(Utils.MESSAGE, "验证成功");
					} else {// g
						map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
						map.put(Utils.MESSAGE, "该合伙人不属于机构");
					}
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "该人员不是合伙人");
				}
			} else {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "该人员不是合伙人");
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "该人员不存在");
		}
		return result;
	}

	// 审核合伙人
	public Map<String, Object> validate_member_partner(ApiT_member_partner apiT_member_partner) throws Exception {
		HashMap<String, Object> result = new HashMap<String, Object>();
		// 这里是系统设置的，最后从cache中获取
		List<ApiT_enums> apiT_enums = apiT_enumsMapper.findT_enumssByItem_key("gold_partner_count");
		Integer maxGoldPartnerCount = Integer.valueOf(apiT_enums.get(0).getItem_value());
		// 现在系统内金牌合伙人数量
		Integer count = apiT_member_partnerMapper.getGoldPartnerCount(1, null);
		if (maxGoldPartnerCount > count) {// 金牌合伙人数量未满
			// 跟新申请资料表
			ApiT_member_partner aMember_partner = apiT_member_partnerMapper
					.findT_member_partnerById(apiT_member_partner.getId());
			Date now = new Date();
			aMember_partner.setApply_uid(apiT_member_partner.getApply_uid());
			aMember_partner.setUpdate_time(DateUtil.dateToString(now, "yyyy-MM-dd HH:mm:ss"));
			aMember_partner.setReason(apiT_member_partner.getReason());
			aMember_partner.setStatus(apiT_member_partner.getStatus());

			// 跟新用户表状态
			ApiT_member apiT_member = apiT_memberMapper.findT_memberById(aMember_partner.getUser_id());
			if (aMember_partner.getStatus() == 1) {// 通过
				apiT_member.setVerify_partner(1);
				// 生成认证编码
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("corp_code", aMember_partner.getCorp_id());
				List<ApiU_org> list = apiU_orgMapper.findU_orgsByMap(map);
				ApiU_org apiU_org = list.get(0);
				// 该人员在该季机构的代码
				String partner_code = getpartner_code(apiU_org);
				apiT_member.setPartner_code(partner_code);

				// 合伙人身份的截止时间
				ApiT_member_partner_task apiT_member_partner_task = apiT_member_partner_taskMapper
						.findT_member_partner_taskById(Integer.valueOf(aMember_partner.getTask_id()));
				Date dateAfter = DateUtil.getDateAfter(now, 1, apiT_member_partner_task.getSign_term());
				aMember_partner.setRule_deadline(DateUtil.dateToString(dateAfter, "yyyy-MM-dd HH:mm:ss"));
				// 审核通过金牌合伙人时则更新为已支付，用户的冻结资金+上保证金
				if ("1".equals(aMember_partner.getTask_id())) {
					aMember_partner.setIs_pay(1);
				}
				// 将保证金更新到用户的冻结资金里去
				apiT_member.setFrozen_money(apiT_member_partner_task.getDeposit());

				ApiT_member_task_process apiT_member_task_process = new ApiT_member_task_process();
				apiT_member_task_process.setFrozen_money(apiT_member_partner_task.getDeposit());
				apiT_member_task_process.setTask_id(aMember_partner.getTask_id());
				apiT_member_task_process.setUser_id(apiT_member.getC_id() + "");
				Date startdate = DateUtil.nowFormatDate("yyyy-MM-dd HH:00:00");
				Date deadtime = DateUtil.getDateAfter(startdate, apiT_member_partner_task.getComplete_time());
				apiT_member_task_process.setDead_time(DateUtil.dateToString(deadtime, "yyyy-MM-dd HH:mm:ss"));
				apiT_member_task_processMapper.T_member_task_processInsertion(apiT_member_task_process);

				// 生成合伙人的二维码
				String qrCodeInfo = QRCodeUtils.baseUrl + "/partner/sq-ziliao.html?code=1:" + partner_code;
				String qrcode_img = QRCodeUtils.createQrCode(qrCodeInfo, 300);
				aMember_partner.setQrcode_img(qrcode_img);
			} else {// 驳回
				apiT_member.setVerify_partner(3);
			}
			apiT_member_partnerMapper.updateT_member_partner(aMember_partner);
			apiT_memberMapper.updateT_member(apiT_member);

			result.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			result.put(Utils.MESSAGE, "审核成功");
		} else {// 金牌合伙人已满后，金牌合伙人待审核状态的人数就是前面排队的人数
			Integer goldPartnerCount = apiT_member_partnerMapper.getGoldPartnerCount(0,
					apiT_member_partner.getId() + "");
			result.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			result.put(Utils.MESSAGE, "金牌合伙人人数已满，您现在排在第" + (goldPartnerCount + 1) + "位");
		}
		return result;
	}

	public ApiT_order getpartnerorderinfo(String id) {
		return apiT_orderMapper.getpartnerorderinfo(id);
	}

	private String getpartner_code(ApiU_org apiU_org) {
		Integer newcur_index = apiU_org.getCur_index() + 1;
		apiU_org.setCur_index(newcur_index);
		apiU_orgMapper.updateU_org(apiU_org);
		String partner_code = apiU_org.getCorp_code();
		if (newcur_index < 10) {
			partner_code += "000" + newcur_index;
		} else if (newcur_index < 100 && newcur_index >= 10) {
			partner_code += "00" + newcur_index;
		} else if (newcur_index < 1000 && newcur_index >= 100) {
			partner_code += "0" + newcur_index;
		} else if (newcur_index < 10000 && newcur_index >= 1000) {
			partner_code += newcur_index;
		}
		return partner_code;
	}

}